<template>
	<div class="export-dialog-view" v-loading="pageLoading">
		<div class="export-dialog">
			<div class="left-lay">
				<div class="split-title">{{ title }}</div>
				<div class="left-line">
					<div class="line-title">
						{{ $t("message.bhView.leftComponents.device") }}
					</div>
					<div class="line-value">{{ $store.state.plantName }}</div>
				</div>

				<div class="left-line">
					<div class="line-title">
						{{ $t("message.bhView.leftComponents.object") }}
					</div>
					<div class="line-value">
						{{
							$store.state.macType == 1
								? $t("message.bhView.leftComponents.machine")
								: $t("message.bhView.leftComponents.piping")
						}}
					</div>
				</div>

				<div class="left-line">
					<div class="line-title">
						{{ $t("message.reportFrom.exportDialog.title_c") }}
					</div>
					<div class="line-value">{{ fileTypeStr }}</div>
				</div>



				<div class="left-draw" id="left-draw"></div>
			</div>

			<div class="tip-lay"></div>

			<div class="right-lay">
				<div class="split-title text-right">
					<i class="el-icon-close" @click="CloseExprotDiloag"></i>
				</div>
				<div class="split-title">
					{{ $t("message.reportFrom.exportDialog.title_l") }}
				</div>
				<div class="right-line">
					<div class="line-title">
						{{ $t("message.ReportFormTable.B_B.lab1") }}
					</div>
				</div>
			</div>
			<div class="FIX">
				<getSvgView v-show="true" ref="cadViewForBH" @changeWait="changeWait" />
			</div>
			<footer class="footer-view">
				<div class="">
					<div class="line-title" style="width: 100%">
						{{ $t("message.reportFrom.exportDialog.tip") }}
					</div>
				</div>
				<div>
					<el-button @click="CloseExprotDiloag">Cancel</el-button>
					<el-button type="primary" @click="onExportClick">OK</el-button>
				</div>
			</footer>
		</div>
	</div>
</template>

<script>
import {
	getLifeAssBaseDate,
	getWindcraftJudgColor,
	getCorrColorData,
	getFile,
	getSvgByFun,
	ExDeviceDrawResReport,
	CollectFiles,
	getPartsMark,
	ExDeviceDrawResReportVerify
} from "@/api/api";
import * as svg_opt from "@/utils/svg_opt.js";
import { getLocalStorage } from "@/utils/storage";
import getSvgView from "./getSvg.vue";
export default {
	props: ["title", "fileTypeStr", "selectMacData", "fileRadio"],
	name: "B_B_Export",
	data() {
		return {
			pageLoading: false,

			LifeAssBaseDate: [],

			corrColorData: [],

			// drawableData 图纸数据
			isSvgLoaded: false,
			svgSourceUrl: "", // 图纸地址
			drawableData: null, // 图纸数据

			markupsPosList: [], // 球标组

			exportDrawContentList: [],
			exportCurrentIndex: 0,
			cachedReDatas: [],

			formExDate: "",
			formCorrRateRule: 4,
			formDailyExType: 1,
			formDeterName: [],
			formCorrRateMark: 1,
			formInspecter: 1,
			formInspectCertificateNo: 1,
			formUpdBeforMeasuredValue: 1,
			formWindcraftJudgColor: "",
			operDate: "",
			state: true
		};
	},
	components: { getSvgView },
	watch: {},
	methods: {
		getLifeAssBaseDateApi() {
			getLifeAssBaseDate().then((res) => {
				if (res.data.code != 0) {
					return;
				}
				res.data.data.forEach((dateItem) => {
					this.LifeAssBaseDate.push({
						label: dateItem,
						value: dateItem,
					});
				});
				this.operDate = this.LifeAssBaseDate[6].value;
			});
		},

		getWindcraftJudgColorApi() {
			getWindcraftJudgColor().then((res) => {
				console.log(res, 333333333333333);
				if (res.data.code != 0) {
					return;
				}
				this.corrColorData = res.data.data;
				this.corrColorData.unshift(this.corrColorData.pop())
				this.formWindcraftJudgColor = this.corrColorData[0].key;
			});
		},

		CloseExprotDiloag() {
			this.$emit("CloseExprotDiloag");
		},

		reloadMachineDrawing(inData) {
			console.log("reloadMachineDrawing --- ", inData);
			let data = {
				DmgCode: inData.macCode,
				PltCode: inData.pltCode,
				FunType: 1
			};

			getSvgByFun(data).then(async (res) => {
				console.log("res---", res);
				this.svgSourceUrl = "";
				let dataJson = res.data.data;

				if (dataJson.length > 0) {
					let item = dataJson[0];
					console.log(item.sourcePath);
					// this.svgSourceUrl = item.sourcePath;
					let inSourceUrl = item.sourcePath;

					this.markupsPosList = await this.getPartsMarkApi(inData.macCode, inData.pltCode);

					let num = inSourceUrl.lastIndexOf(".") + 1;
					this.sourceExt = inSourceUrl.substring(num);
					this.sourceUrl = inSourceUrl;
					var originExt = item.ext;

					let EXT = this.sourceExt.toLowerCase();
					if (
						EXT == "png" ||
						EXT == "jpg" ||
						EXT == "gif" ||
						EXT == "bmp" ||
						EXT == "jpeg" ||
						EXT == "tif" ||
						EXT == "tiff"
					) {
						this.isSourcePic = true;
						this.svgSourceUrl = require("@/assets/model/method-draw-image.svg");
					} else {
						this.isSourcePic = false;
						this.svgSourceUrl = inSourceUrl;
					}

					if (!this.loadSvgWhenReShow) this.loadSvg(originExt);
				}
			});
		},
		async getPartsMarkApi(dmgCode, pltCode) {
			let dataJson = {
				dmgCode,
				pltCode
			};
			let res = await getPartsMark(dataJson)
			if (
				!res.data.data.visualMarkDetials ||
				!res.data.data.visualMarkDetials.length
			) {
				return []
			}
			try {
				res.data.data.visualMarkDetials.forEach(item => {
					item.poS_ORDR_Clone = item.poS_NO
					item.poS_NO = Number(item.num)
				})
				console.log('res.data.data.visualMarkDetials', res.data.data.visualMarkDetials);

			} catch (error) {

			}
			let tempList = this.genVisualBallMarkupsList(
				res.data.data.visualMarkDetials
			);
			return tempList;
		},
		genVisualBallMarkupsList(originData) {
			let reList = [];
			for (let i = 0; i < originData.length; i++) {
				let originItem = originData[i];
				let reListLength = reList.length;
				let reListLastItem =
					reListLength > 0 ? reList[reListLength - 1] : null;

				// 新建一个球标组 球标数组为空 新位置节点与原球标组pos_no不同
				if (
					reListLength == 0 ||
					reListLastItem.pos_no != originItem.poS_NO ||
					(reListLastItem.pos_no == originItem.poS_NO &&
						(reListLastItem.bln_kbn != originItem.blN_KBN ||
							reListLastItem.bln_dtlno != originItem.blN_DTLNO))
				) {
					let ballTemp = {};
					ballTemp.sId = originItem.poS_NO;
					ballTemp.shapeType = Number(originItem.blN_TYPE) + 12;
					ballTemp.showType = "trans";
					ballTemp.showID = originItem.poS_NO;
					ballTemp.lineColor = "#0000ff";
					ballTemp.lineWidth = "5";
					ballTemp.fontSize = originItem.blN_FNTSIZ;
					ballTemp.fontName = originItem.blN_FNTNAM;
					ballTemp.lineStyle = "0";
					ballTemp.points = [];
					ballTemp.bln_kbn = originItem.blN_KBN;
					ballTemp.bln_dtlno = originItem.blN_DTLNO;

					ballTemp.pos_no = originItem.poS_NO;
					ballTemp.ballFillColor = "#00000000";
					ballTemp.allText = originItem.poS_ORDR_Clone;
					ballTemp.points.push({
						bln_x: originItem.blN_X,
						bln_y: originItem.blN_Y,
						x: originItem.blN_X,
						y: originItem.blN_Y,
					});

					reList.push(ballTemp);
				} else {
					reListLastItem.points.push({
						bln_x: originItem.blN_X,
						bln_y: originItem.blN_Y,
						x: originItem.blN_X,
						y: originItem.blN_Y,
					});
				}
			}
			return reList;
		},
		loadSvg(originExt) {
			console.log(this.svgSourceUrl, "this.svgSourceUrl");
			if (!this.svgSourceUrl || this.svgSourceUrl == "") {
				svg_opt.removeSvg();
				this.isSourcePic = false;
				this.markupsPosList = [];
				this.onSvgLoaded();
				return;
			}

			svg_opt.setSvgLineWidthRatio(1.5);
			svg_opt.setSvgBoundingBoxRatio(0, 10, 0.9);
			svg_opt.setCanClickSelectMarkup(false);
			svg_opt.setCanEditSelectMarkup(false);
			svg_opt.setCanFitPositionAndScale(false);
			svg_opt.setEditDotWidthRatio(3);
			svg_opt.AddSvg(this.svgSourceUrl, "left-draw", null,
				false,
				0,
				0,
				originExt == "wmf" ? 1 : -1);
			svg_opt.SetSvgMouseMode(0);
			svg_opt.setLoadCallBack(this.onSvgLoaded);
		},

		async onSvgLoaded(error) {
			if (error) {
				console.log(error);
				return;
			}
			this.isSvgLoaded = true;

			if (this.isSourcePic) {
				svg_opt.changeSvgElementData({
					tagName: "img-content",
					paramName: "xlink:href",
					newValue: this.sourceUrl,
				});
			}
			console.log(this.markupsPosList)
			svg_opt.genMarkupOrignDataFromExternalData(this.markupsPosList);
			var tar = svg_opt.exportSvgDataStr();

			// 请求参数
			let temp = {
				pltCode: this.selectMacData[this.exportCurrentIndex].pltCode,
				macType: this.selectMacData[this.exportCurrentIndex].macType,
				MacNumb: this.selectMacData[this.exportCurrentIndex].macName,
				svgHtml: tar,
				// DmgCode: this.selectMacData[this.exportCurrentIndex].macCode,
			};
			let re = await ExDeviceDrawResReport(temp);
			if (Object.keys(re.data.data).length != 0) {
				this.cachedReDatas.push(re.data.data);
			}


			this.exportCurrentIndex++;
			if (this.exportCurrentIndex < this.selectMacData.length) {
				this.reloadMachineDrawing(
					this.selectMacData[this.exportCurrentIndex]
				);
			} else {
				if (this.cachedReDatas.length <= 0) {
					this.$emit("CloseExprotDiloag");
					this.pageLoading = false;
					this.$alert("No Data", '', {
						confirmButtonText: 'OK',
						type: 'warning',
					});

					return;
				}
				if (this.cachedReDatas.length == 1) {
					this.$emit("CloseExprotDiloag");
					window.open(this.cachedReDatas[0]);
					this.pageLoading = false;
					return;
				}

				let zipRe = await CollectFiles({
					pdfList: this.cachedReDatas,
				}).catch((err) => {
					console.log(err)
					return {
						data: {
							code: -1,
						},
					};
				});

				if (zipRe.data.code == 0) {
					this.$emit("CloseExprotDiloag");
					window.open(zipRe.data.data);
				} else {
					this.$alert(zipRe.data.msg, '', {
						confirmButtonText: 'OK',
						type: 'warning',
					});
				}

				this.pageLoading = false;
				console.log("finished");
			}
		},

		genBallMarkupsList(originData) {
			var reList = [];
			for (var i = 0; i < originData.length; i++) {
				let orignItem = originData[i];
				if (orignItem.poS_ORDR == null) continue;

				let temp = {};
				temp.sId = orignItem.poS_ORDR;
				temp.shapeType = Number(orignItem.blN_TYPE) + 12;
				temp.showType = "trans";
				temp.showID = orignItem.poS_ORDR;
				temp.lineColor = "#0000FF";
				temp.lineWidth = "5";
				temp.fontSize = orignItem.blN_FNTSIZ;
				temp.fontName = orignItem.blN_FNTNAM;
				temp.lineStyle = "0";
				console.log(orignItem.thckBlnPoints)

				if (orignItem.thckBlnPoints.length < 2) {
					// console.log(orignItem.thckBlnPoints)

					// this.$message({
					// 	type: 'error',
					// 	message: '球标数据有缺失'
					// })
					break;
				}
				temp.points = orignItem.thckBlnPoints;
				if (temp.points[0].blN_COLOR)
					temp.ballFillColor = temp.points[0].blN_COLOR;
				else temp.ballFillColor = "#ffffff";
				reList.push(temp);

				for (var j = 0; j < orignItem.thckBlnPoints.length; j++) {
					orignItem.thckBlnPoints[j].x =
						orignItem.thckBlnPoints[j].blN_X;
					orignItem.thckBlnPoints[j].y =
						orignItem.thckBlnPoints[j].blN_Y;
				}
			}
			return reList;
		},
		changeWait(e) {
			this.state = e;
		},
		wait() {
			return new Promise((resolve, reject) => {
				if (this.state) {
					resolve();
				} else {
					const intervalId = setInterval(() => {
						if (this.state) {
							clearInterval(intervalId);
							resolve();
						}
					}, 500);
				}
			});
		},
		async onExportClick() {
			this.pageLoading = true;
			let params = {
				MacNumb: this.selectMacData.map(item => item.macName)
			};
			let F = await ExDeviceDrawResReportVerify(params);
			if (!F) {
				this.pageLoading = false;
				return
			}

			let MacNumb = [];
			let svgHtml = '';
			let pdfList = [];
			for (let index = 0; index < this.selectMacData.length; index++) {
				this.pageLoading = true;
				svgHtml = '';
				let i = this.selectMacData[index];
				MacNumb.push(i.macName)
				this.$refs.cadViewForBH.getSvgByFunFn(
					i.pltCode, i.macCode, 1
				);
				this.state = false;
				await this.wait();
				svgHtml = await this.$refs.cadViewForBH.exportSvgDataStr();

				let dataJson = {
					pltCode: this.selectMacData[0].pltCode,
					macType: this.selectMacData[0].macType,
					MacNumb: this.selectMacData[index].macName,
					svgHtml,
				}
				let res = await ExDeviceDrawResReport(dataJson);
				this.pageLoading = false;
				if (res.data.code != 0 && this.selectMacData.length == 1) {
					this.$alert(res.data.msg, '', {
						confirmButtonText: 'OK',
						type: 'warning',
						callback: action => {
						}
					})
					return
				}
				if (res.data.code == 0) {
					pdfList.push(res.data.data)
				}
			}
			this.pageLoading = false;
			if (pdfList.length == 0) {
				this.pageLoading = false;
				return
			}
			if (pdfList.length == 1) {
				this.$emit("CloseExprotDiloag");
				window.open(pdfList[0]);
			} else {
				let zipRe = await CollectFiles({
					pdfList
				}).catch((err) => {
					console.log(err)
					return {
						data: {
							code: -1,
						},
					};
				});

				if (zipRe.data.code == 0) {
					this.$emit("CloseExprotDiloag");
					window.open(zipRe.data.data);
				} else {
					this.$alert(zipRe.data.msg, '', {
						confirmButtonText: 'OK',
						type: 'warning',
					});
				}
			}
			this.$emit("CloseExprotDiloag");

			this.pageLoading = false;
			return

		},

		getTime() {
			let date = new Date();
			let year = date.getFullYear();
			let mounth = date.getMonth() + 1;
			this.formExDate = `${year}-${mounth}`;
		}
	},
	created() {
		this.getTime();
		this.getLifeAssBaseDateApi();
		this.getWindcraftJudgColorApi();
	},
	mounted() { },
	beforeDestroy() { },
	destroyed() { },
};
</script>
<style lang="scss" scoped>
.export-dialog-view {
	position: fixed;
	width: 100%;
	height: 100%;
	left: 0;
	top: 0;
	z-index: 6;
}

.export-dialog {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 712px;
	height: 280px;
	// height: 292px;
	background: #ffffff;
	box-shadow: 0px 12px 48px 16px rgba(0, 0, 0, 0.05),
		0px 9px 28px 0px rgba(0, 0, 0, 0.08),
		0px 6px 16px -8px rgba(0, 0, 0, 0.15);
	display: flex;
	flex-direction: row;
	padding: 0 12px;
}

.left-lay {
	position: relative;
	width: 40%;
	height: 100%;
	// border-right: 1px solid #ccc;
	display: flex;
	flex-direction: column;
	// background-color: blanchedalmond;

	.left-line {
		width: 100%;
		display: flex;
		flex-direction: row;
		align-items: center;
		padding: 0px 20px;
		padding-top: 10px;

		.line-title {
			font-size: 14px;
			font-weight: 700;
			color: rgba(0, 0, 0, 0.85);
			line-height: 22px;
		}

		.line-value {
			font-size: 14px;
			font-weight: 400;
			color: #7b7b7b;
			line-height: 22px;
			margin-left: 10px;
		}
	}

	.left-draw {
		position: absolute;
		top: 100vh;
		width: 750px;
		height: 611px;
		// flex-grow: 1;
		// flex-shrink: 1;
		background-color: bisque;
	}
}

.tip-lay {
	background: red;
	width: 7px;
	border-radius: 4px;
	background: #ccc;
	margin-top: 46px;
	margin: 46px 15px 85px 15px;
}

.right-lay {
	position: relative;
	width: 60%;
	height: 100%;
	display: flex;
	flex-direction: column;

	.el-icon-close {
		font-size: 16px;
		cursor: pointer;
		width: 46px;
		height: 45px;
		line-height: 45px;
	}

	.right-block-container {
		width: 100%;
		display: flex;
		flex-direction: column;
	}

	.text-right {
		padding: 0 !important;
		text-align: right;
	}

	.right-line {
		width: 100%;
		display: flex;
		flex-direction: row;
		align-items: center;
		padding: 0px 12px;
		padding-top: 10px;

		.line-title {
			font-size: 14px;
			font-weight: 700;
			color: rgba(0, 0, 0, 0.85);
			line-height: 22px;
			text-align: left;
			margin-right: 10px;
		}

		.line-content {
			flex-grow: 1;
			flex-shrink: 1;
			display: flex;
			flex-direction: row;
			align-items: center;
		}

		.ipt {
			//     width: 368px;
			width: 100%;
			height: 32px;

			::v-deep .el-input__inner {
				width: 100%;
				height: 32px;
			}

			::v-deep .el-input__inner:focus {
				border: 1px solid #dcdfe6;
			}

			::v-deep .el-input__icon {
				line-height: 32px;
				color: #909399;
			}

			::v-deep .el-input__suffix {
				width: 32px;
				right: 0;
				background: #dee0e3;
			}
		}

		.picker {
			width: 130px;
			margin: 0px 10px;

			::v-deep .el-input__inner {
				width: 130px;
			}

			::v-deep .el-input__suffix {
				background: transparent;
			}
		}

		.divider {
			width: 100%;
			height: 1px;
			background-color: #f0f0f0;
		}
	}

	.right-line.bottom-border {
		padding-bottom: 10px;
		// border-bottom: 1px solid #f0f0f0;
	}

	.flex-row {
		flex-direction: row;
	}

	.flex-column {
		flex-direction: column;
	}
}

.split-title {
	width: 100%;
	font-size: 16px;
	font-weight: 700;
	color: rgba(0, 0, 0, 0.85);
	line-height: 22px;
	padding: 12px 12px;
	border-bottom: 1px solid #f0f0f0;
}

.footer-view {
	width: calc(100% - 30px);
	box-sizing: border-box;
	position: absolute;
	z-index: 10;
	bottom: 16px;
	// padding: 0 15px;
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: space-between;
	// background-color: red;
	padding-top: 17px;
	border-top: 1px solid #f0f0f0;
	font-size: 16px;
	font-weight: 700;

	button {
		width: 82px !important;
		height: 32px;
		// background: #ffffff;
		// border: 1px solid #d9d9d9;
		margin-left: 12px;
		border-radius: 4px;
		font-size: 14px;
		font-weight: 500;
		line-height: 0;
	}

	button:nth-child(2) {
		// background: #106ebe;
		// color: #fff;
	}
}

.FIX {
	width: 750px;
	height: 611px;
	position: fixed;
	top: -4000px;
	left: -500px;
}
</style>
